package ext

import com.android.build.api.dsl.CommonExtension
import org.gradle.api.Project
import org.gradle.api.plugins.JavaPluginExtension
import org.gradle.kotlin.dsl.configure
import org.gradle.kotlin.dsl.dependencies
import org.gradle.kotlin.dsl.withType
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile

/**
 * Configure base Kotlin options for JVM (non-Android)
 */
internal fun Project.configureKotlinJvm() {
    extensions.configure<JavaPluginExtension> {
        // Up to Java 11 APIs are available through desugaring
        // https://developer.android.com/studio/write/java11-minimal-support-table
        sourceCompatibility = conf.javaVersion
        targetCompatibility = conf.javaVersion
    }

    configureKotlin()
}

fun Project.configureKotlin() {
    // Use withType to workaround https://youtrack.jetbrains.com/issue/KT-55947
    tasks.withType<KotlinCompile>().configureEach {
        kotlinOptions {
            jvmTarget = conf.jvmTarget.target
            freeCompilerArgs = listOf("-Xcontext-receivers")
        }
    }

}

fun configureKotlinAndroid(commonExtension: CommonExtension<*, *, *, *, *, *>) {
    commonExtension.apply {

        compileSdk = conf.compileSdk

        defaultConfig {
            minSdk = conf.minSdk
        }

        buildFeatures {
            buildConfig = true
            viewBinding = true
        }

        compileOptions {
            sourceCompatibility = conf.javaVersion
            targetCompatibility = conf.javaVersion
//            isCoreLibraryDesugaringEnabled = true
        }

        packaging {
            resources {
                excludes += "/META-INF/{AL2.0,LGPL2.1}"
            }
        }

    }
}

fun Project.configureAndroidDep() {
    dependencies {

//        add("coreLibraryDesugaring", libs.findLibrary("desugar-jdk-libs").get())

        add("implementation", libs.findBundle("androidx-core").get())
        add("implementation", libs.findBundle("androidx-lifecycle").get())

        add("implementation", libs.findBundle("coil").get())
        add("implementation", libs.findBundle("koin").get())

        add("implementation", libs.findLibrary("google-gson").get())
        add("implementation", libs.findLibrary("tencent-mmkv").get())
    }
}

fun Project.configureKotlinDep() {
    dependencies {
        add("implementation", libs.findBundle("kotlin-core").get())
    }
}
